package com.ysk.testapplication.qcm.img_load;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Handler;
import android.widget.ImageView;

import com.ysk.testapplication.LOG;

import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

import javax.net.ssl.HttpsURLConnection;


/**
 * @author RQ
 * date    2022-01-27 15:58
 */
public class DefaultProxy implements ImageLoadProxyImpl {
  @Override
  public void display(Context context, Object obj, ImageView view, int defaultRes, int errRes,
                      int width, int height, int moreTag) {
    if (obj == null) {
      LOG.e("DefaultProxy", "display.null");
      return;
    }
    if (obj instanceof String) {
      LOG.e("DefaultProxy", "display.34:" + obj);
    } else {
      LOG.e("DefaultProxy", "默认模式只支持String网络Url,当前加载内容:" + obj.getClass().getSimpleName());
      return;
    }
    final String url = (String) obj;
    new Thread() {
      @Override
      public void run() {
        URL myFileUrl = null;
        Bitmap bitmap = null;
        try {
          myFileUrl = new URL(url);
        } catch (MalformedURLException e) {
          e.printStackTrace();
        }
        try {
          HttpURLConnection conn;
          if (url.startsWith("https")) {
            conn = (HttpsURLConnection) myFileUrl.openConnection();
          } else {
            conn = (HttpURLConnection) myFileUrl.openConnection();
          }
          conn.setDoInput(true);
          conn.connect();
          InputStream is = conn.getInputStream();
          bitmap = BitmapFactory.decodeStream(is);
          is.close();
        } catch (IOException e) {
          e.printStackTrace();
        }
        Bitmap finalBitmap = bitmap;
        view.post(() -> view.setImageBitmap(finalBitmap));
      }
    }.start();
  }
}
